<template>
  <div class="bigbox">
    <div style="margin-bottom: 40px">
      <h1>添加或删除</h1>
    </div>
    <div>
      <table>
        <thead>
          <tr>
            <th>姓名</th>
            <th>年龄</th>
          </tr>
        </thead>
        <tbody>
          <tr>
            <td>
              <input
                type="text"
                placeholder="请输入姓名"
                v-model="data.userForm.uname"
              />
            </td>
            <td>
              <input
                type="text"
                placeholder="请输入年龄"
                v-model="data.userForm.uage"
              />
            </td>
          </tr>
          <tr>
            <td>
              <input type="button" value="确认" @click="saveAE" />
            </td>
            <td>
              <input
                type="button"
                value="返回"
                @click="$router.push({ name: 'users' })"
              />
            </td>
          </tr>
        </tbody>
      </table>
    </div>
  </div>
</template>

<script setup>
  import axios from "axios";
  import { onMounted, reactive } from "vue";
  import { useRoute } from "vue-router";

  const api = "http://localhost:3000";
  const id = useRoute().query.id;
  const data = reactive({
    userForm: {},
  });

  //查询单个用户
  function queryBook() {
    if (id) {
      axios.get(`${api}/user/${id}`).then((res) => {
        console.log(res.data.data);
        data.userForm = res.data.data;
      });
    }
  }

  //添加或修改
  function saveAE() {
    console.log(data.userForm);
    if (id) {
      axios.put(`${api}/user/${id}`, data.userForm).then(() => {
        location.href = "/users";
      });
    } else {
      axios.post(`${api}/user`, data.userForm).then(() => {
        location.href = "/users";
      });
    }
  }

  onMounted(() => {
    queryBook();
  });
</script>

<style scoped>
  * {
    margin: 0px;
    padding: 0px;
  }
  th {
    line-height: 40px;
  }

  tr,
  td {
    border: 1px solid;
    border-collapse: collapse;
    line-height: 30px;
  }

  table {
    width: 600px;
    border-collapse: collapse;
    text-align: center;
    font-family: cursive;
  }

  .bigbox {
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    width: 100vw;
    height: 100vh;
  }
</style>
